﻿using System;

using System.Collections.Generic;

using System.IO;

using System.Text.Json;



public class Student

{

    public string Id { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }



    public Student(string id, string name, int age)

    {

        Id = id;

        Name = name;

        Age = age;

    }



    public override string ToString()

    {

        return $"学号：{Id}，姓名：{Name}，年龄：{Age}";

    }

}



public class StudentJsonHelper

{

    private List<Student> studentList;



    public StudentJsonHelper(List<Student> list) => studentList = list;



    public void SerializeToJson(string filePath)

    {

        string jsonString = JsonSerializer.Serialize(studentList);

        File.WriteAllText(filePath, jsonString);

    }



    public List<Student> DeserializeFromJson(string filePath)

    {

        if (File.Exists(filePath))

        {

            string jsonString = File.ReadAllText(filePath);

            return JsonSerializer.Deserialize<List<Student>>(jsonString);

        }

        return null;

    }

}



class Program

{

    static void Main(string[] args)

    {

        List<Student> students = new List<Student>

        {

            new Student("1001", "张三", 18),

            new Student("1002", "李四", 19)

        };



        StudentJsonHelper helper = new StudentJsonHelper(students);

        string filePath = "students.json";



        helper.SerializeToJson(filePath);

        Console.WriteLine("已序列化并保存到文件");



        List<Student> deserialized = helper.DeserializeFromJson(filePath);

        if (deserialized != null)

        {

            Console.WriteLine("\n反序列化后遍历：");

            foreach (var stu in deserialized)

                Console.WriteLine(stu);

        }

    }

}